import re
import json
from typing import Optional, Dict, Any
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)


resp = '''
user
user
<image>
请仔细分析这张提单图片，提取以下字段信息：

1. 集装箱号 (Container No.)
2. 发货人公司名称 (Shipper/Exporter Company)
3. 发货人地址 (Shipper/Exporter Address)  地址如果包含邮政编码，请带上
4. 收货人公司名称 (Consignee Company)
5. 收货人地址 (Consignee Address) 地址如果包含邮政编码，请带上
6. 包裹数量 (packages)
7. 重量 (weight)
8. 体积 (volume)
9. 货品名称 (goods) 数组类型

请严格按照如下JSON格式返回数据，如果字段不存在请使用空字符串""：
{
"Container No.": "提取到的集装箱号",
"Shipper/Exporter[Company]": "发货公司名称", 
"Shipper/Exporter[Address]": "发货人地址",
"Consignee[Company]": "收货公司名称",
"Consignee[Address]": "收货人地址",
"goods": "货品名称",
"packages": "包裹数量数字",
"weight": "重量数字", 
"volume": "体积数字"

}

请仔细扫描文档的每个部分，特别是表格区域。
assistant

assistant
```json
{
  "Container No.": "",
  "Shipper/Exporter[Company]": "SHENZHEN LANYOU TECHNOLOGY CO., LTD.",
  "Shipper/Exporter[Address]": "",
  "Consignee[Company]": "AVERRA GLOBAL INC",
  "Consignee[Address]": "330 E COSTILLA ST NUM 1020 COLORADO SPGS, CO 80903",
  "goods": [
    "SHIPPER'S LOAD,COUNT AND SEAL(1X40'HQ)CONTAINERS S.T.C.CY-CY STORAGE BOXTHIS SHIPMENT CONTAINS NO SOLID"
  ],
  "packages": 829,
  "weight": 12380.0,
  "volume": 68.0
}
```'''


def extract_json_from_string(text):
    """
    从字符串中提取JSON内容
    """
    # 使用正则表达式匹配JSON格式的内容
    json_pattern = r'\{.*?\}'
    matches = re.findall(json_pattern, text, re.DOTALL)

    for match in matches:
        try:
            # 尝试解析为JSON
            json_data = json.loads(match)
            return json_data
        except json.JSONDecodeError:
            # 如果解析失败，继续尝试下一个匹配
            continue

    return None


def extract_after_assistant_regex(text):
    """
    使用正则表达式匹配assistant后面的内容
    """
    pattern = r'```json\s*(.*)```'  # 匹配assistant后面的所有内容
    match = re.search(pattern, text, re.DOTALL)  # re.DOTALL让.匹配换行符
    if match:
        return match.group(1).strip()
    return ""

if __name__ == '__main__':
    resp = extract_after_assistant_regex(resp)
    print(extract_json_from_string(resp))